import { RouteLocationNormalizedLoaded, RouteRecordRaw } from 'vue-router';
import i18n from '@/locales';

const { t } = i18n.global;

export const guid = () => {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
    const r = (Math.random() * 16) | 0,
      v = c == 'x' ? r : (r & 0x3) | 0x8;
    return v.toString(16);
  });
};

export interface TreeNode<T> {
  children?: T[];
}

export const traverseTree = <T extends TreeNode<T>>(consume: (node: T) => void, roots?: Array<T>) => {
  if (!roots) {
    return;
  }
  roots.forEach(root => {
    consume(root);
    traverseTree(consume, root.children);
  });
};

export const traverseTreeWithParentChildrenAndIndex = <T extends TreeNode<T>>(
  consume: (node: T, parentChildren: Array<T>, index: number) => void,
  nodes?: Array<T>,
) => {
  if (!nodes) {
    return;
  }
  for (let i = 0; i < nodes.length; i++) {
    const node = nodes[i];
    consume(node, nodes, i);
    traverseTreeWithParentChildrenAndIndex(consume, node.children);
  }
};

export const getRouteName = (route: RouteRecordRaw): string => {
  return route.name as string;
};

export const getRouteTitle = (route: RouteRecordRaw): string => {
  const meta = route.meta;
  if (!meta) {
    return '';
  }
  const title = meta.title as string;
  if (!title) {
    return '';
  }
  return t(title);
};

// 递归，从路由中获取值，给路径参数赋值
export const fixPath = (path: string, route: RouteLocationNormalizedLoaded): string => {
  const matches = path.matchAll(/:([a-zA-Z]+)/g);
  for (const match of matches) {
    const key = match[1];
    const value = route.params[key];
    if (value) {
      path = path.replace(`:${key}`, Array.isArray(value) ? value.join(',') : value);
    }
  }
  return path;
};
